<template>
  <div class="Store-management">
    <!-- 店铺基本信息 -->
    <el-card class="Store-info">
      <div class="Store-header">
        <h2>{{ factoryInfo.name }}</h2>
        <el-button type="primary" @click="editfactoryInfo()">编辑店铺信息</el-button>
      </div>
      <div class="Store-content">
        <p>{{ factoryInfo.description }}</p>
        <p>店铺热线: {{ factoryInfo.phone }}</p>
        <p> <i class="icon-location"></i>主卖类型：{{ factoryInfo.type }}</p>
        <p><i class="icon-location"></i>店铺地址：{{ factoryInfo.location }}</p>
        <p><i class="icon-location"></i>开店日期：{{ formattedDate }}</p>
      </div>
    </el-card>

    <!-- 地址簿 -->
    <el-card class="address-book">
      <div class="address-header">
        <h3>地址簿</h3>
        <el-button type="success" @click="addNewAddress">新增地址</el-button>
      </div>
      <!-- 地址列表 -->
        <div class="address-list">
          <div class="address-item" v-for="(item, index) in addressList" :key="index">
            <div class="address-content">
              <p class="region">{{ item.province }} {{ item.city }} {{ item.district }}</p>
              <p class="street">{{ item.detail }}</p>
              <p class="contact">{{ item.name }} {{ item.phone }}</p>
            </div>
            <div class="address-actions">
              <el-button type="primary" @click="editAddress(item)">编辑</el-button>
              <el-button type="info" @click="deleteAddress(item.addressId)">删除</el-button>
            </div>
          </div>
        </div>
    </el-card>

    <!-- 编辑店铺信息弹窗 -->
    <el-dialog v-model="StoreDialogVisible" title="编辑店铺信息">
      <el-form :model="editingFactory" label-width="100px">
        <el-form-item label="店铺名称">
          <el-input v-model="editingFactory.name" />
        </el-form-item>
        <el-form-item label="店铺热线">
          <el-input v-model="editingFactory.phone" />
        </el-form-item>
        <el-form-item label="店铺地址">
          <el-input v-model="editingFactory.location" />
        </el-form-item>
        <el-form-item label="店铺主卖">
          <el-input v-model="editingFactory.type" />
        </el-form-item>
        <el-form-item label="店铺描述">
          <el-input v-model="editingFactory.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="StoreDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savefactoryInfo">确定</el-button>
      </template>
    </el-dialog>

    <!-- 地址编辑弹窗 -->
    <el-dialog v-model="addressDialogVisible" :title="isEdit ? '编辑地址' : '新增地址'" width="40%">
      <el-form :model="addressInfo" label-width="100px" >
        <el-form-item label="收货人" required>
          <el-input v-model="addressInfo.name" />
        </el-form-item>
        <el-form-item label="手机号码" required>
          <el-input v-model="addressInfo.phone" />
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input style="margin-top: 3px;" v-model="addressInfo.province" placeholder="请输入省份"/>
          <el-input style="margin-top: 3px;" v-model="addressInfo.city" placeholder="请输入市"/>
          <el-input style="margin-top: 3px;" v-model="addressInfo.district" placeholder="请输入区县"/>
          <el-input style="margin-top: 3px;" v-model="addressInfo.detail" placeholder="请输入详细地址"/>
        </el-form-item>
        <el-form-item label="默认地址">
          <el-cascader
            v-model="addressInfo.is_default"
            :options="isDefault"
            placeholder="是否设为默认地址"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getFactoryInfoAPI, updateFactoryInfoAPI, getAddressListAPI,addAddressAPI, updateAddressAPI, deleteAddressAPI } from '@/api/factory'
import { useTokenStore } from '@/store/token';

// 用户信息
const tokenStore = useTokenStore()
const user = tokenStore.user;

// 店铺信息
const factoryInfo = reactive({
  factoryId: '',
  name: '',
  phone: '',
  keeperName: '',
  location: '',
  description:'',
  type: '',
  createTime: ''
})
// 店铺信息编辑对象
const editingFactory = reactive({
  factoryId: '',
  name: '',
  phone: '',
  keeperName: '',
  location: '',
  description:'',
  type: '',
})

// 获取店铺信息
function getFactoryInfo() {
  getFactoryInfoAPI(user.userId).then(res => {
    if (res.code === 0) {
      console.log(res.data);
      factoryInfo.factoryId = res.data.factoryId
      editingFactory.factoryId = res.data.factoryId
      addressInfo.userId = res.data.userId
      factoryInfo.name = res.data.factoryName
      factoryInfo.phone = res.data.phone
      factoryInfo.keeperName = res.data.keeperName
      factoryInfo.location = res.data.location
      factoryInfo.description = res.data.description
      factoryInfo.type = res.data.type
      factoryInfo.createTime = res.data.createTime
      tokenStore.setFactory(res.data)
    } else {
      ElMessage.error(res.message)
    }
  })
}
getFactoryInfo();

const formattedDate = computed(() => {
  // 将 createTime 字符串转换为 Date 对象
  const date = new Date(factoryInfo.createTime);
  // 格式化日期为 yyyy-mm-dd
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
});

//提交店铺保存方法
const savefactoryInfo  = async () => { 
  //调用接口提交店铺修改请求
  let data = {factoryId: editingFactory.factoryId, factoryName: editingFactory.name, phone: editingFactory.phone, location: editingFactory.location, type: editingFactory.type, description: editingFactory.description}
  await updateFactoryInfoAPI(data).then(res => {
    console.log(res.data)
    StoreDialogVisible.value = false
    ElMessage.success('保存成功')
    getFactoryInfo();
  }).catch(err => {
    console.log(err)
  })
}

// 是否是默认地址
const isDefault = ref([
  { label: '是', value: 'Y' },
  { label: '否', value: 'N' }
])

// 地址列表
const addressList = ref([])

// 弹窗控制
const StoreDialogVisible = ref(false)
const addressDialogVisible = ref(false)
const isEdit = ref(false)

//地址编辑对象
const addressInfo = reactive({
  addressId: '',
  userId: '',
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  is_default: 'N'
})

// 店铺信息相关方法
const editfactoryInfo = () => {
  Object.assign(editingFactory, factoryInfo)
  // console.log(editingFactory);
  StoreDialogVisible.value = true
}

// 获取实体店收货地址列表
function getAddressList() {
  getAddressListAPI(user.userId).then(res => {
    console.log(res);
    if (res.code === 0) {
      addressList.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  })
}
getAddressList()

// 新增地址方法
const addNewAddress = () => {
  isEdit.value = false
  //清空数据
  clearaddressInfo()
  addressDialogVisible.value = true
}
//打开地址弹框
const editAddress = (row) => {
  isEdit.value = true
  Object.assign(addressInfo, row)
  addressDialogVisible.value = true
}

console.log(addressInfo);
//提交保存地址方法
const saveAddress = () => {
  if (isEdit.value) {
    // 编辑地址
    updateAddressAPI(addressInfo).then(res => {
      console.log(res);
      if (res.code === 0) {
        ElMessage.success('编辑地址成功')
      } else{
        ElMessage.error(res.message)
      }
      //重新获取地址列表
      getAddressList();
    })
  } else {
    // 新增地址
    addAddressAPI(addressInfo).then(res=>{
      if(res.code === 0){
        ElMessage.success('添加地址成功')
      } else{
        ElMessage.error(res.message)
      }
      //重新获取地址列表
      getAddressList();
    })
  }
  addressDialogVisible.value = false
  ElMessage.success('保存成功')
  //重新获取地址列表
  getAddressList();
}
//删除地址方法
const deleteAddress =  (id) => {
  ElMessageBox.confirm('确定要删除该地址吗？', '提示', {
    type: 'warning'
  }).then(() => {
    // 调用接口删除
    deleteAddressAPI(id).then(res => {
      if (res.code === 0) {
        ElMessage.success('删除成功')
      } else if (res.code === 1) {
        ElMessage.error('删除失败，不存在该地址信息！')
      } else {
        ElMessage.error(res.message)
      }
      //重新获取地址列表
      getAddressList();
    })
    //重新获取地址列表
    getAddressList();
  })
}


// 清空编辑对象的方法
function clearaddressInfo() {
  addressInfo.region = '';
  addressInfo.detail = '';
  addressInfo.name = '';
  addressInfo.phone = '';
  addressInfo.is_default = 'N';
}
</script>

<style scoped>
.Store-management {
  padding: 20px;
}

.Store-info, .address-book {
  margin-bottom: 20px;
}

.Store-header, .address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.Store-content {
  line-height: 1.8;
}

.address-list {
  background-color: white;
  border-radius: 4px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  padding: 1rem 0;
  border-bottom: 1px solid #eee;
}

.address-actions {
  display: flex;
  gap: 1rem;
}

.edit-btn, .delete-btn {
  padding: 0.25rem 0.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.edit-btn {
  background-color: #f0f0f0;
}

.delete-btn {
  background-color: #fff;
  border: 1px solid #ddd;
}
</style>